<template>
  <div class="product-card-wrap">
    <div class="product-card-item" v-for="(item, index) in cardList" :key="index">
      <div class="product-card-li">
        <div class="card-name">
          <p class="name">{{ $t('common.connector.title.additionalCard') }}</p>
          <span class="del" @click="onDel(index)"><i class="iconfont icon-delete"></i></span>
        </div>
        <el-select 
          v-model="item.cardField" 
          :placeholder="$t('common.placeholder.select')" 
          value-key="id"
          filterable 
          @change="(value)=>changeAdditional(value, index)">
          <el-option 
            v-for="card in cardInfoList" 
            :key="card.id" 
            :label="card.name" 
            :value="card"
          > 
          </el-option>
        </el-select>
      </div>
      <div class="product-card-li">
        <div class="card-name">
          <p class="name">{{ $t('common.base.concatField') }}</p>
        </div>
        <el-select 
          v-model="item.cardLinkerField" 
          :placeholder="$t('common.placeholder.select')" 
          :multiple-limit="10"
          filterable 
          value-key="fieldName"
          multiple
          clearable
          @change="(value)=>changeCardLinkerField(value, index)">
          <el-option 
            v-for="(ele, indx) in cardFieldObj[item.cardField.id]" 
            :key="indx" 
            :label="ele.displayName" 
            :value="ele"
          > 
          </el-option>
        </el-select>
      </div>
      <div class="product-card-li">
        <div class="card-name">
          <p class="name">{{$t('setting.enterprise.quickEntrance.customLink.icon')}}</p>
        </div>
          <el-popover placement="right" :width="380" trigger="click">
          <div class="select-app-icon-logo">
            <div class="app-icon">
              <div v-for="colorObj in iconColors" :key="colorObj.color" class="logo-color"
                :style="{ background: `${colorObj.color}` }" @click="selectColor(colorObj.color, index)">
                <i v-if="colorObj.color == item.color" class="iconfont icon-duihao1" />
              </div>
            </div>
            <div class="app-logo">
              <div v-for="(icon, idx) in iconList" :key="idx" class="app-logo-item"
                @click="selectAppIcon(icon.className, index)">
                <div class="appIcon">
                  <i :class="['iconfont', icon.className]"
                    :style="{ color: icon.className == item.icon ? item.color : '' }" />
                </div>
              </div>
            </div>
          </div>
          <div class="apply-icon" slot="reference">
            <div class="icon" :style="{ background: item.color }">
              <i :class="['iconfont', item.icon]"></i>
            </div>
            <span>{{$t('product.qrcodeSetting.paasApplyTemplate.clickText')}}</span>
          </div>
        </el-popover>

      </div>
    </div>
    <div class="add-apply" @click="addApply">
      <p>+ {{ $t('event.setting.serviceEventTypeSetting.flow.component.title1') }}</p>
    </div>
  </div>
</template>
  <script>
/* api */
import { getEnabledCardInfo } from '@src/api/SettingCusProApi';
import  { getCardFieldList } from '@src/api/SettingCusProApi';
/* service */
import { isConnectorCard } from '@service/CardService';
/* util */
import { iconColors, iconList, Default_Logo, Default_Color } from '../util/appIconList.ts';
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum.ts'
import i18n from '@src/locales';
// 过滤签名、分割线、说明信息、附件, 备件关联字段
const FILTER_SPECIAL_FORM = [
  FieldTypeMappingEnum.Autograph,
  FieldTypeMappingEnum.Separator,
  FieldTypeMappingEnum.Info,
  FieldTypeMappingEnum.Attachment,
  FieldTypeMappingEnum.relationReplacementPart,
];
export default {
  name: 'product-card-item',
  props: {
    productCardList: {
      type:Array,
      default:[]
    },
  },
  data() {
    return {
      iconColors,
      iconList,
      isConnectorCard,
      cardList: [],
      cardInfoList: [],
      cardFieldObj: {},
      defaultField:[
        {
          displayName: i18n.t('common.base.operator'),
          fieldName: 'userName',
          formType: 'text'
        },
        {
          displayName: i18n.t('common.label.operationTime'),
          fieldName: 'updateTime',
          formType: "datetime"
        } 
      ]
    };
  },
  mounted() {
    this.cardList = this.productCardList;
    this.fetchCardTemplateList();
    this.initCardDate()
  },
  methods: {
    /** 设置颜色 */
    selectColor(color, index) {
    this.cardList[index].color = color;
    },
    /** 设置icon */
    selectAppIcon(icon, index) {
      this.cardList[index].icon = icon;
    },
    initCardDate() {
      this.productCardList.map(item =>{
        if(item?.cardField?.id) {
          this.fetchCardFieldList(item?.cardField?.id, null)
        }
      })
    },
    changeCardLinkerField(value, index){
      this.cardList[index].cardLinkerField = value.sort((a, b) => a.orderId - b.orderId);
    },
    /** 选择附加组件 */
    changeAdditional(card, index) {
      this.cardList[index].cardLinkerField = [];
      this.fetchCardFieldList(card.id, index);
    },
    /** 添加应用 */
    addApply() {
      this.cardList.push({
        cardField: {},
        cardLinkerField: [],
        color: Default_Color,
        icon: Default_Logo,
      });
      this.$emit('updateProductCard', this.cardList);
    },
    /** 删除 */
    onDel(index) {
      this.cardList.splice(index, 1);
    },
    /* 查询表单模板列表 */
    async fetchCardTemplateList() {
      try {
        const { result, code, message } = await getEnabledCardInfo({ cardType: 'product' });
        if (code !== 0) return;

        this.cardInfoList = (result || []).filter(item => item?.specialfrom !== '连接器');
      } catch (error) {
        console.log(error);
      }
    },
    /* 获取附加组件表单field */
    async fetchCardFieldList(id,index) {
      try {
        const params = {
          cardType: 'product',
          id
        }
        const { result, code, message } = await getCardFieldList(params);
        if (code !== 0) return;
        const cardFields = (result || []).filter(item =>!FILTER_SPECIAL_FORM.includes(item.formType));
        this.upDataCardField(cardFields, id, index);
      } catch (error) {
        console.log(error);
      }
    },
    /** 更新选择的附加组件表单字段数据 */
    upDataCardField(cardFields, id, index) {
      const relatedFields = [...cardFields, ...this.defaultField];
      // 增加orderId属性 用于排序
      relatedFields.forEach((field, idx) => {
        field.orderId = idx;
      });
      this.cardFieldObj[id] = relatedFields;

      if(cardFields.length > 0) {
        if((index || index == 0) && this.cardList?.[index]?.cardLinkerField?.length == 0){
          this.cardList[index].cardLinkerField = [...new Set([...relatedFields.slice(0, 3), ...relatedFields.slice(-2)])];
        }
        this.$forceUpdate()
      }
    }
  },
};
</script>
  <style lang="scss" scoped>
.product-card-wrap {
  color: $text-color-primary;
  background: #fff;

  .product-card-item {
    background: #f2f2f2;
    margin: 10px 0;
    padding: 12px;

    .product-card-li {
      .el-input {
        margin-bottom: 10px;
      }
      .el-select {
        width: 100%;
        margin-bottom: 10px;
      }

      .card-name {
        display: flex;
        justify-content: space-between;
        line-height: 22px;
        margin-bottom: 2px;

        p {
          margin-bottom: 0px;
        }

        .del {
          cursor: pointer;
        }
      }

      .apply-icon {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        cursor: pointer;
        .icon {
          width: 40px;
          height: 40px;
          border-radius: 12px;
          cursor: pointer;
          line-height: 40px;
          text-align: center;
          .iconfont {
            color: #fff;
            font-size: 18px;
          }
        }

        span {
          margin-left: 8px;
          color: $text-color-secondary;
        }
      }
    }
  }

  .add-apply {
    margin-top: 10px;

    p {
      background: #f5f8fa;
      border: 1px solid #cbd6e2;
      // width: 377px;
      height: 32px;
      border-radius: 4px;
      line-height: 32px;
      text-align: center;
      font-size: 14px;
      color: $text-color-regular;
      cursor: pointer;
    }
  }
}

.select-app-icon-logo {
  .app-icon {
    display: flex;
  }

  .logo-color {
    display: inline-flex;
    width: 24px;
    height: 24px;
    border-radius: 12px;
    margin-right: 12px;
    justify-content: center;
    align-items: center;

    i {
      color: #fff;
    }
  }

  .app-logo {
    max-height: 274px;
    overflow: auto;
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    padding: 14px 0 !important;
    margin: 0 !important;

    .app-logo-item {
      width: 50px;
      height: 50px;
      border-radius: 4px;
      border: 1px solid #d9d9d9;
      margin: 6px;
      display: flex;
      align-items: center;
      justify-content: center;

      i {
        font-size: 25px;
      }
    }
  }
}
</style>